{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "3087421f-4a65-4a20-aed7-66d4471ccd3e",
   "metadata": {},
   "source": [
    "# 第一周实验"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4bedb29c-2c15-49f1-ad70-871bfa76e1f3",
   "metadata": {},
   "source": [
    "欢迎来到第一周实验  \n",
    "本周实验将带领大家完成Anaconda的安装，以及介绍人工智能实验中常用的python基础语法，这是我们学习人工智能的第一步！"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7d3738ad-8dc9-4d4f-b9a1-e20428d25a3e",
   "metadata": {},
   "source": [
    "# 安装Anaconda"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fd99838a-0a5a-4f89-bbf7-625e181507a8",
   "metadata": {},
   "source": [
    "Anoconda是一个开源的Python数据科学平台，包含了Conda（一个开源的软件包管理系统和环境管理系统）、Python解释器，以及超过250个预装的科学和机器学习包。\n",
    "其安装流程简便，并且能方便地管理虚拟环境，同时拥有丰富的库和工具。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "91c276fb-085b-43de-81ca-a71e8f295bfc",
   "metadata": {},
   "source": [
    "## 第一步：下载Anaconda"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "89c2d901-98b6-4b4b-a4f1-81bfefc7b28a",
   "metadata": {},
   "source": [
    "前往官方网站下载：[https://www.anaconda.com/download/success](https://www.anaconda.com/download/success)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "908217b8-3ddc-4c5e-807a-94e1193f4219",
   "metadata": {},
   "source": [
    "![](./图片/2.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ec3874e8-2933-4c1f-8712-c8703ac51f0d",
   "metadata": {},
   "source": [
    "## 第二步：安装Anaconda"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b9256d71-aa42-4d97-a522-840a48fb48ba",
   "metadata": {},
   "source": [
    "选择\"just me\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c2218aff-10c7-4794-9ff0-d4512b6488f7",
   "metadata": {},
   "source": [
    "[](./图片/3.png)\n",
    "<img src=./图片/3.png width=500>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2dee1be7-8c1d-4b48-a53f-4f960841be58",
   "metadata": {},
   "source": [
    "设置安装路径,这里设置在D盘"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6944a816-ba4c-4938-b1bf-d3a0deb662a2",
   "metadata": {},
   "source": [
    "[](./图片/4.png)\n",
    "<img src=./图片/4.png width=500>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bb2f3933-763d-4950-bd65-13d2aa78aef9",
   "metadata": {},
   "source": [
    "勾选前3个，点击install开始安装"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "aea3b42d-5379-4fec-8e3c-ce4c1bfcfa18",
   "metadata": {},
   "source": [
    "[](./图片/5.png)\n",
    "<img src=./图片/5.png width=500>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7ecd0122-5b03-4de5-8581-c353edf96f96",
   "metadata": {},
   "source": [
    "安装完成"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "599e8e9e-3e33-4f52-ae0e-7bf0b039733a",
   "metadata": {},
   "source": [
    "[](./图片/6.png)\n",
    "<img src=./图片/6.png width=500>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "db2cd7b0-2066-4217-b5b5-b242592db32d",
   "metadata": {},
   "source": [
    "## 第三步：完成安装"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7151aae8-bbc9-4fd5-8cd5-ab6e231852bb",
   "metadata": {},
   "source": [
    "安装完成后，你就可以使用Anaconda以及jupyter notebook了  \n",
    "打开Anaconda导航器，在Enviroments中可以看到电脑已有的虚拟环境，右边是该环境中安装的包"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "61a0cb1f-13f8-4a1c-9501-b75112795818",
   "metadata": {},
   "source": [
    "[](./图片/7.png)\n",
    "<img src=./图片/7.png width=800>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "205ff6bb-7aa2-469d-a55e-a0bac4cd9e22",
   "metadata": {},
   "source": [
    "## 第四步：使用jupyter notebook\n",
    "Jupyter Notebook 是一个开源的 Web 应用程序，允许用户创建和共享包含实时代码、方程、可视化和解释性文本的文档。它具有可交互式编程的特点，大大地方便了我们编程"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9ee92023-4c0b-4710-ada8-ff60aa1f97fc",
   "metadata": {},
   "source": [
    "新建一个文件夹，在该文件的索引栏输入cmd，回车，进入终端  \n",
    "（若想打开已有的jupyter notebook，则在对应的文件夹的索引栏输入cmd进入终端）"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ef64954d-bf5f-4f4c-9dbb-10cff4cfa1e2",
   "metadata": {},
   "source": [
    "[](./图片/8.png)\n",
    "<img src=./图片/8.png width=600>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d09f5737-810b-4804-8af9-d4d19fe8e7b1",
   "metadata": {},
   "source": [
    "在终端输入``jupyter notebook``，回车，启动jupyter notebook服务（默认端口号为8888）"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ab21fb5d-fac9-4846-a6d7-445f8edc1acc",
   "metadata": {},
   "source": [
    "[](./图片/9.png)\n",
    "<img src=./图片/9.png width=600>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f24ad672-100a-4ec7-866d-2b0e5e11b4b3",
   "metadata": {},
   "source": [
    "第一个地址即是服务的网页地址，按住ctrl点击该地址即可打开，或者在浏览器输入``localhost:8888``也可打开网页"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d540d2d9-2ca6-4f36-a4ca-9dcd376c404f",
   "metadata": {},
   "source": [
    "[](./图片/10.png)\n",
    "<img src=./图片/10.png width=600>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1ee90a52-6d33-4392-a951-2ded6d9fc005",
   "metadata": {},
   "source": [
    "成功打开jupyter notebook后，点击new，再点击第一个，即可创建一个新的python笔记"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "af3c0ac0-9524-4154-bb3b-ed97db087518",
   "metadata": {},
   "source": [
    "[](./图片/11.png)\n",
    "<img src=./图片/11.png width=800>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fe3f0605-472f-4ff2-b951-7dafda26a1f3",
   "metadata": {},
   "source": [
    "我们可以使用jupyter notebook运行Python代码  \n",
    "在一个单元格内输入代码后，按**shift+enter**即可加载该单元格内的所有代码，如下图第1行单元格所示，输入print(''helloworld'')，再按shift+enter即可执行该行代码，输出结果  \n",
    "其他各种使用技巧和快捷键可以上网自行查询并掌握  \n",
    "**注意，jupyter notebook前面的单元格加载的代码能够作用于后续的所有单元格。**\n",
    "如下图所示，我在第2行单元格内定义了一个变量a为整数100，按shift+enter运行。在第3行定义了变量b为整数200并打印a+b的值，按shift+enter运行，输出得到300"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "120750f6-38b4-4505-8f09-92c039981c4d",
   "metadata": {},
   "source": [
    "[](./图片/12.png)\n",
    "<img src=./图片/12.png width=800>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "aaf3f87e-48b8-4d39-afd6-54d150266035",
   "metadata": {},
   "source": [
    "# Python的基础练习"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e180c92c-a836-4296-a851-8170f9e067b0",
   "metadata": {},
   "source": [
    "以下是人工智能实验中常用的python基础语法  \n",
    "大家可以新建一个jupyter notebook，仿照案例，在单元格内输入案例中的某一行或某一段代码，按**shift+enter**运行，看看结果如何     \n",
    "**注意#后面的字是对该行代码的注释**  "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ed4e855e-baa0-4bba-8f6c-058f2fa05689",
   "metadata": {
    "jp-MarkdownHeadingCollapsed": true
   },
   "source": [
    "## 练习一：掌握基础数据类型"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "eb8a189a-d60e-497f-8a06-913c79cf008a",
   "metadata": {},
   "source": [
    "Python中最基本的数据类型包括整型，浮点数，布尔值和字符串。类型是不需要声明的，比如："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d5a16a28-e55a-4552-9e6a-7ec5004e197a",
   "metadata": {},
   "outputs": [],
   "source": [
    "a=1     # 定义一个变量a，a的值为整数1  \n",
    "b=1.2   # 浮点数\n",
    "c=True  # 布尔类型，其值只能为True或False\n",
    "d=\"abcd\"# 字符串\n",
    "e=None  # NoneType，注意不是0，在很多API中，如果执行失败就会返回None。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2e85d5ed-7432-46fe-b4e5-868039c0773e",
   "metadata": {},
   "source": [
    "## 练习二：缩进与代码块"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6ba5a3ed-29a3-4e68-bb9a-287877074938",
   "metadata": {},
   "source": [
    "用缩进替代C语言的{}：相同缩进视为同一代码块（一般用4空格，按TAB即可实现缩进）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "c2b64920-d522-4dda-b1dc-a454a4c90afc",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "正数\n"
     ]
    }
   ],
   "source": [
    "x = 3\n",
    "if x > 0:        # 条件语句，若x>0则输出正数，反之则输出非正数\n",
    "    print(\"正数\")\n",
    "else:\n",
    "    print(\"非正数\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d938dff3-c6ef-460c-a66f-ab960f0b87db",
   "metadata": {},
   "source": [
    "## 练习三：运算符"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "57e085d1-a3bb-460d-ac59-69866c7f6276",
   "metadata": {},
   "source": [
    "Python中的数值的基本运算和C差不多，字符串的运算更方便，下面是常见的例子："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "ec224532-8333-40de-893c-3c488bea7aa7",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3\n"
     ]
    }
   ],
   "source": [
    "a = 2\n",
    "b = 2.3         \n",
    "c = 3\n",
    "a + b           # 2 + 2.3 = 4.3\n",
    "c - a           # 3 - 2 = 1\n",
    "a / b           # 整数除以浮点数，运算以浮点数为准，2 / 2.3 = 0.8695652173913044\n",
    "a / c           # Python2中，整数除法，向下取整 2 / 3 = 0\n",
    "a ** c          # a的c次方，结果为8\n",
    "a += 1          # Python中没有i++的用法，自增用+=\n",
    "c -= 3          # c变成0了\n",
    "# 取模运算\n",
    "c = 7\n",
    "d = c % 4\n",
    "print(d)    #3\n",
    "d = 'Hello'     \n",
    "d + ' world!'   # 相当于字符串拼接，结果为'Hello world!'\n",
    "d += ' \"world\"!'# 相当于把字符串接在当前字符串尾，d变为'Hello \"world\"!'"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f8de6c81-16f1-4c36-a805-d7707ef2cfc3",
   "metadata": {},
   "source": [
    "需要提以下的几点：1）字符串用双引号和单引号都可以，区别主要是单引号字符串中如果出现单引号字符则需要用转义符，双引号也是一样，所以在单引号字符串中使用双引号，或者双引号字符串中使用单引号就会比较方便。另外三个双引号或者三个单引号围起来的也是字符串，因为换行方便，更多用于文档。2）Python2中两个数值相除会根据数值类型判断是否整数除法，Python3中则都按照浮点数。想要在Python2中也执行Python3中的除法只要执行下面语句："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "e9d29290-5ddb-41c3-9d3b-6aa7b9352386",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from __future__ import division     # 使用Python3中的除法\n",
    "1 / 2                                   # 0.5\n",
    "1//2                               #0，舍去小数，只保留整数部分"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "63d3b12d-a73f-43a0-99c7-e31ae4b869a4",
   "metadata": {},
   "source": [
    "and / or /not介绍："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "a95907ab-aaa6-4c0e-84d8-88ff66cac67c",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x>3 and x<5  #表示x大于3且小于5\n",
    "x>3 or x<5 #表示x大于3或x小于5\n",
    "a = True\n",
    "b = False\n",
    "a and b     # False\n",
    "a or b      # True\n",
    "not a       # False"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8d0dc8ab-db0e-4354-b382-eb6a2a6aef12",
   "metadata": {},
   "source": [
    "**大家自己可以新建一个jupyter notebook，动手练习一下各种运算，例如：**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "e0a9700c-f70f-42f0-9ca3-2932f8d19052",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "c的值为：helloworld\n"
     ]
    }
   ],
   "source": [
    "a='hello'       #定义一个字符串a\n",
    "b='world'       #定义一个字符串b\n",
    "c=a+b           #将a+b的值赋值给c\n",
    "print('c的值为：'+c)       #输出c的值，按shift+enter运行该单元格的代码,单元格下面会出现结果"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bbc75dd6-a1d3-4a88-a7d7-438ac80edb0d",
   "metadata": {},
   "source": [
    "## 练习四：注释"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d3ae3025-77e1-458a-ab94-22580524f326",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 单行注释"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "59683e5c-9ee2-470b-aa44-999f12985b7c",
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"\n",
    "多行注释\n",
    "多行注释\n",
    "多行注释\n",
    "\"\"\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5b6ce55e-eecf-4049-8608-4af30915951e",
   "metadata": {},
   "source": [
    "## 练习五：模块导入"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8d033361-f558-45c4-9845-d557a2fb639c",
   "metadata": {},
   "source": [
    "因为提到了对象名覆盖和import，所以简单讲一下。import是利用Python中各种强大库的基础，比如要计算cos(π)的值，可以有下面4种方式："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "e91b0c40-efe1-4089-8789-ed6b2e898e16",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "-1.0\n",
      "-1.0\n",
      "-1.0\n",
      "-1.0\n"
     ]
    }
   ],
   "source": [
    "# 直接导入Python的内置基础数学库\n",
    "import math\n",
    "pi = math.pi\n",
    "cospi=math.cos(pi)\n",
    "print(cospi)    #-1\n",
    "\n",
    "# 从math中导入cos函数和pi变量\n",
    "from math import cos, pi\n",
    "cospi=cos(pi)\n",
    "print(cospi)    #-1\n",
    "\n",
    "# 如果是个模块，在导入的时候可以起个别名，避免名字冲突或是方便懒得打字的人使用\n",
    "import math as m\n",
    "pi = m.pi\n",
    "cospi=m.cos(pi)\n",
    "print(cospi)     #-1\n",
    "\n",
    "# 从math中导入所有东西\n",
    "from math import *\n",
    "cospi=cos(pi)\n",
    "print(cospi)    #-1"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "be01bb8d-6a14-410c-9bd3-8483c559a1fc",
   "metadata": {},
   "source": [
    "一般来说导入所有内容的方式不是很推荐，因为不知道import导入的名字里是否和现有对象名已经有冲突，很可能会不知不觉覆盖了现有的对象。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0623ced5-835a-43ae-8fee-dfd037b8ac56",
   "metadata": {},
   "source": [
    "math包的常见运算"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "6fb9a410-9f95-4dc6-95ca-b07fed413aa6",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2.0\n",
      "1.0 1.0\n",
      "8.0\n",
      "2\n"
     ]
    }
   ],
   "source": [
    "import math\n",
    "\n",
    "# 使用math中的开方运算\n",
    "a = 4\n",
    "b = math.sqrt(a)\n",
    "print(b)     #2\n",
    "\n",
    "# 使用math取绝对值\n",
    "e = -1\n",
    "f = 1\n",
    "print(math.fabs(e),math.fabs(f))   #|1|=|-1|=1\n",
    "\n",
    "# 使用math去做次方运算math.pow(x, y): 返回x的y次幂。\n",
    "print(math.pow(2,3))    #2^3=8\n",
    "\n",
    "# math.ceil(x): 返回大于或等于x的最小整数。\n",
    "print(math.ceil(1.1))     #2"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "777ec24e-5650-461e-abfb-7ee7d7c87e40",
   "metadata": {},
   "source": [
    "随机数生成random函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "1d4c63c3-18df-4cbf-aff9-72463efa57e3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "float in range: 1.4195892197062072\n",
      "int in range: 85\n",
      "step int in range: 12\n",
      "random in a list: 3\n"
     ]
    }
   ],
   "source": [
    "import random\n",
    "\n",
    "# 生成随机浮点数 范围 0 ~ 1\n",
    "a=random.random()\n",
    "\n",
    "# 生成指定范围内的浮点数\n",
    "smallfloat = 1.1\n",
    "bigfloat = 1.5\n",
    "print(\"float in range:\",random.uniform(smallfloat,bigfloat))\n",
    "\n",
    "# 生成指定范围的随机整数\n",
    "smallnum = 1\n",
    "bignum = 100\n",
    "print(\"int in range:\",random.randint(smallnum,bignum))\n",
    "\n",
    "# 生成指定范围内的指定步幅的随机整数\n",
    "smallnum = 0\n",
    "bignum = 100\n",
    "step = 3\n",
    "print(\"step int in range:\",random.randrange(smallnum,bignum,step))\n",
    "\n",
    "# 从列表序列中随机取一个数\n",
    "mylist = [1,2,3,4,5,6,7,8,9]\n",
    "print(\"random in a list:\",random.choice(mylist))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3ab3a170-bf82-4f65-8753-7cd248837105",
   "metadata": {},
   "source": [
    "## 练习六：容器  \n",
    "列表(list)是一个有序且可更改的集合，并且是最常用的 Python 数据类型。  \n",
    "在Python中，列表中元素的数据类型可以不同，可以包含整数、浮点、字符串等，当然，也可以包含列表、元组、字典和集合等。  \n",
    "在 Python 中，列表是使用方括号 “[]” 编写的，在列表中使用“逗号（，）”来将列表中的元素隔断。当“[]”内没有元素时，该列表为空。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7fbb2809-9771-4986-b70b-1e17cc74b282",
   "metadata": {},
   "source": [
    "### 1.列表  "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e75bd942-b74c-4b60-b17d-1b239bbec7ba",
   "metadata": {},
   "source": [
    "创建一个列表，里面包含1，2，3，4，其中用逗号隔开"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "92f9021f-5cce-49d1-9b02-8f1e81550d95",
   "metadata": {},
   "outputs": [],
   "source": [
    "a = [1, 2, 3, 4]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "40a597a5-c930-411c-95df-565b3836322d",
   "metadata": {},
   "source": [
    "列表的基本操作有访问，增加，删除，和拼接："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ae4c6673-cfba-4ccb-af1c-7a6513bb7ef6",
   "metadata": {},
   "outputs": [],
   "source": [
    "a.pop()             # 把最后一个值4从列表中移除并作为pop的返回值\n",
    "a.append(5)         # 末尾插入值，[1, 2, 3, 5]\n",
    "a.index(2)          # 找到第一个2所在的位置，也就是1\n",
    "a[0]                #读取列表的第一个元素\n",
    "a[-1]               #读取列表的最后一个元素\n",
    "a[2]                # 取下标，也就是位置在2的值，也就是第三个值3\n",
    "a[3] = 9            # 指定下标处赋值，[1, 2, 3, 9]\n",
    "a += [4, 3, 2]      # 拼接，[1, 2, 3, 9, 4, 3, 2]\n",
    "a.insert(1, 0)      # 在下标为1处插入元素0，[1, 0, 2, 3, 9, 4, 3, 2]\n",
    "a.remove(2)         # 移除第一个2，[1, 0, 3, 9, 4, 3, 2]\n",
    "a.reverse()         # 倒序，a变为[2, 3, 4, 9, 3, 0, 1]\n",
    "a.sort()            #列表内排序，a变为[0, 1, 2, 3, 3, 4, 9]\n",
    "len(a)              # 获取列表a的长度"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1b29136f-f478-4d1e-b84d-f7283f39a7e4",
   "metadata": {},
   "source": [
    "列表的切片"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ed295c84-98fb-4fe3-ad92-16b84722762d",
   "metadata": {},
   "outputs": [],
   "source": [
    "b=a[:] #b=[1,2,3,4],从头开始读取列表的元素直到结尾，\n",
    "c=a[1:]  #c=[2,3,4],从下标为1的元素开始读取直到结尾\n",
    "d=a[::-1] #d=[4,3,2,1],从尾部一直读到头\n",
    "e=a[1:3]   #e=[2,3],取第一个元素至第二个元素\n",
    "f=a[0:-1] #f=[1,2,3], 不包含最后一个元素"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3af00039-677c-474a-a2c8-a4442ea06b6b",
   "metadata": {},
   "source": [
    "### 2.字典  \n",
    "字典是一种非常常见的“键-值”(key-value)映射结构，键无重复，一个键不能对应多个值，不过多个键可以指向一个值。还是通过例子来了解，构建一个名字->年龄的字典，并执行一些常见操作："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "834d94fd-0271-436b-ba11-879721bb1504",
   "metadata": {},
   "outputs": [],
   "source": [
    "a = {'Tom': 8, 'Jerry': 7}\n",
    "print(a['Tom'])             # 8\n",
    "b = dict(Tom=8, Jerry=7)    # 一种字符串作为键更方便的初始化方式\n",
    "print(b['Tom'])             # 8\n",
    "if 'Jerry' in a:            # 判断'Jerry'是否在keys里面\n",
    "    print(a['Jerry'])        # 7\n",
    "print(a.get('Spike'))       # None，通过get获得值，即使键不存在也不会报异常\n",
    "a['Spike'] = 10\n",
    "a['Tyke'] = 3\n",
    "a.update({'Tuffy': 2, 'Mammy Two Shoes': 42})\n",
    "print(a.values())   # dict_values([8, 2, 3, 7, 10, 42])\n",
    "print(a.pop('Mammy Two Shoes'))     # 移除'Mammy Two Shoes'的键值对，并返回42\n",
    "print(a.keys())     # dict_keys(['Tom', 'Tuffy', 'Tyke', 'Jerry', 'Spike']) "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2a39b205-0e1d-4bc9-a02a-925d51994d57",
   "metadata": {},
   "source": [
    "## 练习七：for循环"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8ceed3cb-27cb-4b5e-b607-981c226896eb",
   "metadata": {},
   "source": [
    "range函数介绍：  \n",
    "range() 是 Python 内置的一个函数，用于生成一个整数序列。具体来说，它的定义如下：  \n",
    "``range([start], [stop], [step]) ``   \n",
    "start、stop、step 分别表示序列的起始值、终止值和步长。start 和 step 是可选参数，如果不指定则默认为 0 和 1。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "560a2af5-f8d9-4dc4-b18d-0c9d22a829c7",
   "metadata": {},
   "outputs": [],
   "source": [
    "a=list(range(5))    #a=[0,1,2,3,4],range(5) 表示生成一个从 0 开始、小于 5 的整数序列\n",
    "b=list(range(1,5,1))  #a=[1,2,3,4],表示生成一个从1开始，小于5，整数之间间隔为1的序列,等同于range(1,5)\n",
    "c=list(range(1,11,2))        #取出奇数，c=[1, 3, 5, 7, 9]\n",
    "d=list(range(0,11,2))        #取出偶数，d=[0, 2, 4, 6, 8, 10]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c6c3f32e-4e92-4e28-aeb6-be174522a32c",
   "metadata": {},
   "source": [
    "for循环介绍："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2516450b-e346-4c27-8e17-335c80c0b21c",
   "metadata": {},
   "outputs": [],
   "source": [
    "a=[1,2,3,4]\n",
    "\n",
    "# 遍历列表a的所有元素,每次循环都会将a中的一个元素赋值给x\n",
    "for x in a:\n",
    "    print(x)    #1,2,3,4\n",
    "    \n",
    "# 下面代码会从0-9，共循环10次，这个range(10)，其实是相当于产生一个从0-9的列表，每循环一次，就会把列表里的下一个元素取出来给临时变量i。\n",
    "for i in range(10):\n",
    "    print(i)    #0,1,2,3,4,5,6,7,8,9"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bedcc603-8450-4429-b1d9-79f0d0b4cf1c",
   "metadata": {},
   "source": [
    "## 练习八：字符串"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7abcfa81-d735-4f5e-98b0-14a10a253822",
   "metadata": {},
   "source": [
    "Python中字符串相关的处理都非常方便，来看例子："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "28646fbb-95a9-417c-b507-d0312c44944a",
   "metadata": {},
   "outputs": [],
   "source": [
    "a = 'Life is short, you need Python'\n",
    "a.lower()              \t# 'life is short, you need Python'\n",
    "a.upper()               \t# 'LIFE IS SHORT, YOU NEED PYTHON'\n",
    "a.count('i')            \t# 2\n",
    "a.find('e')             \t# 从左向右查找'e'，3\n",
    "a.rfind('need')         \t# 从右向左查找'need'，19\n",
    "a.replace('you', 'I')   # 'Life is short, I need Python'\n",
    "tokens = a.split()    \t# ['Life', 'is', 'short,', 'you', 'need', 'Python']\n",
    "b = ' '.join(tokens)\t# 用指定分隔符按顺序把字符串列表组合成新字符串\n",
    "c = a + '\\n'            \t# 加了换行符，注意+用法是字符串作为序列的用法\n",
    "c.rstrip()              \t# 右侧去除换行符\n",
    "[x for x in a]          \t# 遍历每个字符并生成由所有字符按顺序构成的列表\n",
    "'Python' in a   \t\t\t# True"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "124d7afc-ff45-4e8d-ade5-c0fc44dccacd",
   "metadata": {},
   "source": [
    "## 练习九：函数"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b8cd94d7-f828-4efd-a57e-b185b02878b3",
   "metadata": {},
   "source": [
    "  在编程的过程中，我们可以把一些频繁使用的过程语句封装到一个函数中，需要使用时直接调用函数，而不用在代码中频繁的使用同一段过程语句。这样做即减少了写代码的工作量，又使代码的逻辑更加清晰。所以我们要学会合理的定义函数，来使我们写的代码短而强。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d9a0a3a3-d427-4012-aa7a-8d94196bea35",
   "metadata": {},
   "outputs": [],
   "source": [
    "基本结构：\n",
    "# 无参函数定义\n",
    "def 函数名():\n",
    "    函数内的逻辑语句\n",
    " \n",
    "# 无参函数调用方式\n",
    "函数名()\n",
    " \n",
    "# 有参函数定义\n",
    "def 函数名(参数名1, 参数名2, ..., 参数名n):\n",
    "    函数内的逻辑语句\n",
    " \n",
    "# 有参函数调用方式\n",
    "函数名(值1, 值2, ..., 值n)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9eae761b-8d84-4709-b1db-2a001d11bbc3",
   "metadata": {},
   "source": [
    "下面举例说明："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "c58a665f-76f9-4366-8004-2b7ed251e7d9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello!\n",
      "Good morning!\n",
      "What's up!\n",
      "Good morning!\n",
      "1\n",
      "2\n",
      "3\n",
      "A\n",
      "B\n",
      "C\n",
      "D\n",
      "x 3\n",
      "y 4\n",
      "z 5\n",
      "fighter1 Fedor\n",
      "fighter2 Randleman\n",
      "1 2\n",
      "(3, 4, 5)\n",
      "{'a': 6, 'b': 'bar'}\n"
     ]
    }
   ],
   "source": [
    "def say_hello():\n",
    "    print('Hello!')\n",
    "\n",
    "def greetings(x='Good morning!'):\n",
    "    print(x)\n",
    "\n",
    "say_hello()                 \t\t# Hello!\n",
    "greetings()                 \t\t# Good morning!\n",
    "greetings(\"What's up!\")     \t\t# What's up!\n",
    "a = greetings()             \t\t# 返回值是None\n",
    "\n",
    "def create_a_list(x, y=2, z=3):\t# 默认参数项必须放后面\n",
    "    return [x, y, z]\n",
    "\n",
    "b = create_a_list(1)        \t\t# [1, 2, 3]\n",
    "c = create_a_list(3, 3)     \t\t# [3, 3, 3]\n",
    "d = create_a_list(6, 7, 8)  \t        # [6, 7, 8]\n",
    "\n",
    "def traverse_args(*args):\n",
    "    for arg in args:\n",
    "        print(arg)\n",
    "\n",
    "traverse_args(1, 2, 3)              # 依次打印1, 2, 3\n",
    "traverse_args('A', 'B', 'C', 'D')   # 依次打印A, B, C, D\n",
    "\n",
    "def traverse_kargs(**kwargs):\n",
    "    for k, v in kwargs.items():\n",
    "        print(k, v)\n",
    "\n",
    "traverse_kargs(x=3, y=4, z=5)       # 依次打印('x', 3), ('y', 4), ('z', 5)\n",
    "traverse_kargs(fighter1='Fedor', fighter2='Randleman')\n",
    "\n",
    "def foo(x, y, *args, **kwargs):\n",
    "    print(x, y)\n",
    "    print(args)\n",
    "    print(kwargs)\n",
    "\n",
    "# 第一个pring输出(1, 2)\n",
    "# 第二个print输出(3, 4, 5)\n",
    "# 第三个print输出{'a': 3, 'b': 'bar'}\n",
    "foo(1, 2, 3, 4, 5, a=6, b='bar')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f9b00d3b-c7c1-4858-b714-5ddd88103060",
   "metadata": {},
   "source": [
    "其实和很多语言差不多，括号里面定义参数，参数可以有默认值，且默认值不能在无默认值参数之前。Python中的返回值用return定义，如果没有定义返回值，默认返回值是None。参数的定义可以非常灵活，可以有定义好的固定参数，也可以有可变长的参数(args: arguments)和关键字参数(kargs: keyword arguments)。如果要把这些参数都混用，则固定参数在最前，关键字参数在最后。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "598aa5b3-c495-4c18-9d35-da370fe001e5",
   "metadata": {},
   "source": [
    "## 练习十：类"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c3877387-436d-48ba-be4e-8ca93f15267b",
   "metadata": {},
   "source": [
    "Python中的类的概念和其他语言相比没什么不同，比较特殊的是protected和private在Python中是没有明确限制的，一个惯例是用单下划线开头的表示protected，用双下划线开头的表示private："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "748e446d-5b6b-4964-83ff-8b2cf3c1f952",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Class A\n",
      "Leonardo\n",
      "What's up!\n",
      "Leonardo\n",
      "242\n",
      "242\n"
     ]
    },
    {
     "ename": "AttributeError",
     "evalue": "'A' object has no attribute '__l2norm'",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mAttributeError\u001b[0m                            Traceback (most recent call last)",
      "Cell \u001b[1;32mIn[26], line 27\u001b[0m\n\u001b[0;32m     25\u001b[0m \u001b[38;5;28mprint\u001b[39m(a\u001b[38;5;241m.\u001b[39mcal_l2norm())   \u001b[38;5;66;03m# 输出11*11+11*11=242\u001b[39;00m\n\u001b[0;32m     26\u001b[0m \u001b[38;5;28mprint\u001b[39m(a\u001b[38;5;241m.\u001b[39m_A__l2norm())   \u001b[38;5;66;03m# 仍然可以访问，只是名字不一样\u001b[39;00m\n\u001b[1;32m---> 27\u001b[0m \u001b[38;5;28mprint\u001b[39m(a\u001b[38;5;241m.\u001b[39m__l2norm())     \t\u001b[38;5;66;03m# 报错: 'A' object has no attribute '__l2norm'\u001b[39;00m\n\u001b[0;32m     28\u001b[0m \u001b[38;5;124;03m\"\"\"\u001b[39;00m\n\u001b[0;32m     29\u001b[0m \u001b[38;5;124;03m在类 A 中，__l2norm 方法被 Python 自动改名为 _A__l2norm（在类名前加单下划线）。这是一种名称改写机制，目的是让这个方法在类外不容易被直接访问，实现某种程度的\"私有化\"。\u001b[39;00m\n\u001b[0;32m     30\u001b[0m \n\u001b[1;32m   (...)\u001b[0m\n\u001b[0;32m     36\u001b[0m \n\u001b[0;32m     37\u001b[0m \u001b[38;5;124;03m类内部的方法（如 cal_l2norm）可以正常调用 __l2norm，因为名称改写是在类定义时完成的，类内部知道正确的名称。\"\"\"\u001b[39;00m\n",
      "\u001b[1;31mAttributeError\u001b[0m: 'A' object has no attribute '__l2norm'"
     ]
    }
   ],
   "source": [
    "class A:\n",
    "    \"\"\"Class A\"\"\"\n",
    "    def __init__(self, x, y, name):\n",
    "        self.x = x\n",
    "        self.y = y\n",
    "        self._name = name\n",
    "\n",
    "    def introduce(self):\n",
    "        print(self._name)\n",
    "\n",
    "    def greeting(self):\n",
    "        print(\"What's up!\")\n",
    "\n",
    "    def __l2norm(self):\n",
    "        return self.x**2 + self.y**2\n",
    "\n",
    "    def cal_l2norm(self):\n",
    "        return self.__l2norm()\n",
    "\n",
    "a = A(11, 11, 'Leonardo')\n",
    "print(A.__doc__)        \t# \"Class A\"\n",
    "a.introduce()           \t# \"Leonardo\"\n",
    "a.greeting()            \t# \"What's up!\"\n",
    "print(a._name)          \t# 可以正常访问\n",
    "print(a.cal_l2norm())   # 输出11*11+11*11=242\n",
    "print(a._A__l2norm())   # 仍然可以访问，只是名字不一样\n",
    "print(a.__l2norm())     \t# 报错: 'A' object has no attribute '__l2norm'\n",
    "\"\"\"\n",
    "在类 A 中，__l2norm 方法被 Python 自动改名为 _A__l2norm（在类名前加单下划线）。这是一种名称改写机制，目的是让这个方法在类外不容易被直接访问，实现某种程度的\"私有化\"。\n",
    "\n",
    "当你尝试直接调用 a.__l2norm() 时，Python 会按照原名称查找这个方法，但找不到，因为实际名称已经被改写了。\n",
    "\n",
    "你仍然可以通过改写后的名称 a._A__l2norm() 来访问这个方法，如你代码中所示。\n",
    "\n",
    "这种名称改写不是真正的私有化（Python 没有真正的私有成员），只是一种约定俗成的机制，让开发者知道这些成员不应该被外部直接访问。\n",
    "\n",
    "类内部的方法（如 cal_l2norm）可以正常调用 __l2norm，因为名称改写是在类定义时完成的，类内部知道正确的名称。\"\"\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "41533da9-8ddd-4326-97d5-9395a603345c",
   "metadata": {},
   "source": [
    "类的初始化使用的是__init__(self,)，所有成员变量都是self的，所以以self.开头。可以看到，单下划线开头的变量是可以直接访问的，而双下划线开头的变量则触发了Python中一种叫做name mangling的机制，其实就是名字变了下，仍然可以通过前边加上“_类名”的方式访问。也就是说Python中变量的访问权限都是靠自觉的。类定义中紧跟着类名字下一行的字符串叫做docstring，可以写一些用于描述类的介绍，如果有定义则通过“类名.__doc__”访问。这种前后都加双下划线访问的是特殊的变量/方法，除了__doc__和__init__还有很多，这里就不展开讲了。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "47a7a2c2-3165-41ce-a14a-6c4d7321845f",
   "metadata": {},
   "source": [
    "## 练习十一：文件与数据读写"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6d4a2175-4543-461f-82c1-3e6c0879231e",
   "metadata": {},
   "source": [
    "读取文件主要用到两个方式，即：  \n",
    "1. with方式"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "6d5ad297-0831-44a6-8c80-f45bcfab9231",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a\n",
      "b\n",
      "c\n",
      "d\n",
      "e\n",
      "f\n",
      "g\n",
      "h\n",
      "i\n",
      "j\n",
      "k\n",
      "l\n",
      "m\n",
      "n\n",
      "o\n",
      "p\n",
      "q\n",
      "r\n",
      "s\n",
      "t\n",
      "u\n",
      "v\n",
      "w\n",
      "x\n",
      "y\n",
      "z\n"
     ]
    },
    {
     "ename": "ValueError",
     "evalue": "I/O operation on closed file.",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mValueError\u001b[0m                                Traceback (most recent call last)",
      "Cell \u001b[1;32mIn[1], line 8\u001b[0m\n\u001b[0;32m      3\u001b[0m     \u001b[38;5;28mprint\u001b[39m(contents)\n\u001b[0;32m      4\u001b[0m \u001b[38;5;66;03m# 退出 with 块后，文件自动关闭\u001b[39;00m\n\u001b[0;32m      5\u001b[0m \n\u001b[0;32m      6\u001b[0m \u001b[38;5;66;03m# 这里尝试读取已经关闭的文件，导致报错\u001b[39;00m\n\u001b[0;32m      7\u001b[0m \u001b[38;5;66;03m#  表示逐行读取\u001b[39;00m\n\u001b[1;32m----> 8\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m line \u001b[38;5;129;01min\u001b[39;00m file_object:\n\u001b[0;32m      9\u001b[0m     \u001b[38;5;28mprint\u001b[39m(line)\n",
      "\u001b[1;31mValueError\u001b[0m: I/O operation on closed file."
     ]
    }
   ],
   "source": [
    "with open('./abc.txt') as file_object:\n",
    "    contents = file_object.read() # 会把整个文件内容读入 contents，文件指针会移动到文件末尾。\n",
    "    print(contents)\n",
    "# 退出 with 块后，文件自动关闭\n",
    "\n",
    "# 这里尝试读取已经关闭的文件，导致报错\n",
    "#  表示逐行读取\n",
    "for line in file_object:\n",
    "    print(line)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3857b446-9f77-4b63-9641-f8aacebc9892",
   "metadata": {},
   "source": [
    "2. open方式  \n",
    "open方法直接打开并读取文件，不使用with语句，此方法直接读取文件，但是要记得关闭文件，我们要知道，我们操作的是什么，目的是什么，如果我们只是单纯的读取文件的内容，而不去修改它，那么就单纯使用open()方法，不用第二参数即可。函数open（）接受一个参数：要打开文件的名称。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "5c061c95-c4e1-4eb6-9eb9-16599c849f46",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a\n",
      "b\n",
      "c\n",
      "d\n",
      "e\n",
      "f\n",
      "g\n",
      "h\n",
      "i\n",
      "j\n",
      "k\n",
      "l\n",
      "m\n",
      "n\n",
      "o\n",
      "p\n",
      "q\n",
      "r\n",
      "s\n",
      "t\n",
      "u\n",
      "v\n",
      "w\n",
      "x\n",
      "y\n",
      "z\n",
      "['a\\n', 'b\\n', 'c\\n', 'd\\n', 'e\\n', 'f\\n', 'g\\n', 'h\\n', 'i\\n', 'j\\n', 'k\\n', 'l\\n', 'm\\n', 'n\\n', 'o\\n', 'p\\n', 'q\\n', 'r\\n', 's\\n', 't\\n', 'u\\n', 'v\\n', 'w\\n', 'x\\n', 'y\\n', 'z']\n"
     ]
    }
   ],
   "source": [
    "f = open('./abc.txt')\n",
    "    \n",
    "    # 读取整个文件\n",
    "contents = f.read()\n",
    "print(contents)\n",
    " \n",
    "    #组行读取\n",
    "for line in f:\n",
    "    print(line.strip())\n",
    "\n",
    "file_object=open('./abc.txt')\n",
    "    # 读取文件内容到一个列表中\n",
    "lines = file_object.readlines()\n",
    "print(lines)\n",
    "f.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "35fa3b5a-9f14-4920-b367-e7800b22e5d6",
   "metadata": {},
   "source": [
    "3. open（）函数和with open（）的异同点\n",
    "- with 语句在不再需要访问文件后将其关闭。让python自己判断什么时候该关闭，并自己去关闭。\n",
    "- 直接使用open()方法打开文件，要自己调用close()方法关闭文件。如果程序存在bug，导致close()语句未执行，文件将不会关闭。这看似微不足道，但未妥善地关闭文件可能会导致数据丢失或受损。如果在程序中过早地调用close(),我们会发现需要使用文件时它已关闭(无法访问)，这会导致更多的错误。并非任何情况下都能轻松地确定关闭文件的恰当时机。\n",
    "- open()后是一个对象，这个对象有read()方法与write()方法。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "389891d9-9a57-45f4-b866-0a5bf4875899",
   "metadata": {},
   "source": [
    "## 📝 实验总结"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3a68991e-06d7-4ff1-8186-5d31e6ba73f8",
   "metadata": {},
   "source": [
    "通过本周实验的学习，我们掌握了：\n",
    "- Anaconda的安装\n",
    "- jupyter notebook的使用\n",
    "- python的基础语法"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "41f7f8f8",
   "metadata": {},
   "source": [
    "作业1：计算阶乘\n",
    "编写一个函数，计算并返回正整数 n 的阶乘（即 n! = 1*2*3*...*n）。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "46053f74",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "120\n"
     ]
    }
   ],
   "source": [
    "def factorial(n):\n",
    "    result=1\n",
    "    # 计算阶乘的递归函数\n",
    "    result=n*factorial(n-1) if n>1 else 1\n",
    "    return result\n",
    "# 测试\n",
    "print(factorial(5))  # 输出 120"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c2b7d699",
   "metadata": {},
   "source": [
    "作业2：判断素数\n",
    "编写一个函数，判断一个正整数是否为素数（仅能被 1 和自身整除）。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "05bd806d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n",
      "False\n"
     ]
    }
   ],
   "source": [
    "def is_prime(n):\n",
    "    ret=True\n",
    "    # 判断是否素数的函数 ret为函数的返回值\n",
    "    if n<2:\n",
    "        ret=False\n",
    "    for i in range(2,n):\n",
    "        if n%i==0:\n",
    "            ret=False\n",
    "            break\n",
    "    return ret\n",
    "\n",
    "# 测试\n",
    "print(is_prime(17))  # 输出 True\n",
    "print(is_prime(9))   # 输出 False"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "23b4fbb2",
   "metadata": {},
   "source": [
    "作业3：反转字符串\n",
    "编写一个函数，将输入的字符串反转并返回结果。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "f3d8b33c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "olleh\n"
     ]
    }
   ],
   "source": [
    "def reverse_string(s):\n",
    "    s = s[::-1]\n",
    "    return s\n",
    "\n",
    "# 测试\n",
    "print(reverse_string(\"hello\"))  # 输出 \"olleh\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "22feb33e",
   "metadata": {},
   "source": [
    "作业4：斐波那契数列\n",
    "生成斐波那契数列的前 n 项（例如：0, 1, 1, 2, 3, 5, 8...）。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "c2614c65",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0, 1, 1, 2, 3, 5]\n"
     ]
    }
   ],
   "source": [
    "def fibonacci(n):\n",
    "    a, b = 0, 1\n",
    "    result = []\n",
    "    # 生成斐波那契数列\n",
    "    for i in range(n):\n",
    "        result.append(a)\n",
    "        a, b = b, a + b\n",
    "    return result\n",
    "\n",
    "# 测试\n",
    "print(fibonacci(6))  # 输出 [0, 1, 1, 2, 3, 5]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "68938f20",
   "metadata": {},
   "source": [
    "作业5：找出列表中的最大值\n",
    "编写一个函数，不使用内置函数 max()，找出列表中的最大值。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "944682a3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "9\n"
     ]
    }
   ],
   "source": [
    "def find_max(lst):\n",
    "    max_val = lst[0]\n",
    "    # 找出列表中的最大值\n",
    "    for val in lst:\n",
    "        if val > max_val:\n",
    "            max_val = val\n",
    "    return max_val\n",
    "\n",
    "# 测试\n",
    "print(find_max([3, 7, 2, 9, 1]))  # 输出 9"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "efd00897-9eb3-4efc-afb3-b56ef48ef987",
   "metadata": {},
   "source": [
    "**建议你在课下尝试：**  \n",
    "- 利用jupyter notebook练习巩固以上基础语法的使用\n",
    "- 去python官方文档中进一步学习https://docs.python.org/zh-cn/3.13/index.html\n",
    "- 遇到不懂的地方勤问ai和百度，最高效的学习方式是动手实践，遇到不会的就及时查询"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a5e01f5f-f247-452f-9d2e-8292cc0fac26",
   "metadata": {},
   "source": [
    "大家加油呀，掌握好基础，才能更好地学习后续课程，领略到人工智能的魅力！"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2a5f603d-2e76-4241-bcdf-a45bbdbbdc73",
   "metadata": {},
   "outputs": [],
   "source": [
    "import argparse\n",
    "#可以在pycharm中尝试用命令行来运行下面的python代码\n",
    "#进入目录后输入命令 python .\\formalDemo.py --input abc --output test\n",
    "def parse_args():\n",
    "    \"\"\"解析命令行参数\"\"\"\n",
    "    parser = argparse.ArgumentParser(description='程序描述')\n",
    "    parser.add_argument('--input', help='输入文件')\n",
    "    parser.add_argument('--output', help='输出文件')\n",
    "    return parser.parse_args()\n",
    "\n",
    "def main():\n",
    "    args = parse_args()\n",
    "    print(f\"处理输入: {args.input}, 输出到: {args.output}\")\n",
    "\n",
    "if __name__ == \"__main__\":\n",
    "    main()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "torch",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.23"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
